import { defineStore } from 'pinia'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import remainingRouter from '@/router/modules/remaining'
import { generateRoute, flatMultiLevelRoutes } from '@/utils/routerHelper'
import { getAsyncRoutes } from '@/api/login'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { getAutoLoginParam } from '@/utils/auth'

const { wsCache } = useCache()

export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  menuTabRouters: AppRouteRecordRaw[]
}

function filterChildrenRecursively(item, menus) {
  const childFilterate = ref<any>([])

  if (item.children && item.children.length > 0) {
    item.children.forEach((child: any) => {
      if (menus.includes(String(child.id))) {
        childFilterate.value.push(child)
        filterChildrenRecursively(child, menus)
      }
    })
  }

  item.children = childFilterate.value
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    menuTabRouters: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    }
  },
  actions: {
    async generateRoutes(): Promise<unknown> {
      return new Promise<void>(async (resolve) => {
        // let res: AppCustomRouteRecordRaw[]
        // if (wsCache.get(CACHE_KEY.ROLE_ROUTERS)) {
        //   res = wsCache.get(CACHE_KEY.ROLE_ROUTERS) as AppCustomRouteRecordRaw[]
        //   console.log('res1', res, wsCache.get(CACHE_KEY.ROLE_ROUTERS))
        // } else {
        //   res = await getAsyncRoutes()
        //   console.log('res33', res)

        //   const LoginParam = getAutoLoginParam()
        //   if (LoginParam && LoginParam.menus) {
        //     const menus = LoginParam.menus
        //     console.log(1315, menus)

        //     if (menus.length > 0) {
        //       const menuFilterate = ref<any>([])
        //       res.forEach((item: any) => {
        //         if (menus.includes(String(item.id))) {
        //           // 你可以调用这个函数来开始递归过滤
        //           filterChildrenRecursively(item, menus)

        //           // const childFilterate = ref<any>([])
        //           // if (item.children && item.children.length > 0) {
        //           //   item.children.forEach((child: any) => {
        //           //     if (menus.includes(child.id)) {
        //           //       childFilterate.value.push(child)
        //           //       如果child还有children那就执行类似上一层的代码
        //           //     }
        //           //   })
        //           // }
        //           // item.children = childFilterate.value
        //           menuFilterate.value.push(item)
        //         }
        //       })
        //       console.log('menuFilterate', menuFilterate.value)
        //       res = menuFilterate.value
        //     }
        //   }
        // }
        // wsCache.set(CACHE_KEY.ROLE_ROUTERS, res)
        // const routerMap: AppRouteRecordRaw[] = generateRoute(res as AppCustomRouteRecordRaw[])
        // 动态路由，404一定要放到最后面
        // this.addRouters = routerMap.concat([
        //   {
        //     path: '/:path(.*)*',
        //     redirect: '/404',
        //     name: '404Page',
        //     meta: {
        //       hidden: true,
        //       breadcrumb: false
        //     }
        //   }
        // ])
        // 渲染菜单的所有路由
        this.routers = cloneDeep(remainingRouter)
        resolve()
      })
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    }
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
